home *** CD-ROM | disk | FTP | other *** search
- Path: news.tiac.net!usenet
- From: jnield@versanet.com (jnield@versanet.com)
- Newsgroups: comp.lang.c
- Subject: Re: Help: 2 short functions
- Date: Sat, 30 Mar 1996 08:57:46 GMT
- Organization: VersaNet International
- Message-ID: <4jit3o$f7l@news.tiac.net>
- References: <4ji734$n6v@masala.cc.uh.edu> <29MAR199622515778@erich.triumf.ca>
- Reply-To: jnield@versanet.com
- NNTP-Posting-Host: nield.tiac.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- bennett@erich.triumf.ca (P.Bennett) wrote:
-
- >In article <4ji734$n6v@masala.cc.uh.edu>, st7jr@Rosie.UH.EDU writes...
- >>Hi, I have two functions that I'm not too sure about.
- >>The first one:
- >>
- >>char *get_filename(void)
- >>{
- >> char string[20],*stringp;
- >> scanf("%s",string);
- >> stringp=&string[0];
- >> return stringp;
- >>}
- >>I'm want the function to read in a string and return a pointer to that string.
- >>Am I doing it correctly?
-
- >You don't need stringp - you could simply do "return string;" EXCEPT that
- >string[] will cease to exist when the function returns, and may be over-written
- >at any time.
-
- >You could do:
- > ....
- > static char string[20];
- > ....
- > return string;
-
- >but you must then remember not to call the function again until you have used
- >(or copied) the first string.
-
- >You have the same problem in the second function.
-
- Personally, I would pass the address of an array to the function as a
- param, and have the function read the string into the array (remember,
- the array name is a pointer to the first element of the array).
-
- main()
- {
- char string[20];
- get_filename(string);
- }
-
- void get_filename(char *string)
- {
- scanf("%s",string);
- }
-
- /* see the next example for open_file() */
-
- ... seems like a waste doesn't it...
-
-
- But if there is a reason you can't do that(??), you might try this:
-
- char *get_filename(void)
- {
- char *string;
- string = (char *)malloc(20 * sizeof(char) );
- /* allocate memory for 20 chars on the heap */
- scanf("%s", string);
- return(string);
- }
-
- /* course, you now have to remember to free the memory! */
-
- FILE *open_file(char *filenamep)
- {
- FILE *fp;
- if ( !(fp=fopen(filenamep,"r")) )
- {failbad();}
- /* a string literal is turned into a
- character pointer when it is compiled, so
- you can use filenamep as the string for fopen.
- */
- free(filenamep); /* assuming you want to do it now...
- 'string' and all other pointers to the string
- are now junk. */
- return fp;
- }
-
-
- Hope this was somewhat helpfull. You might find a lot of usefull info
- in the comp.lang.c FAQ at
-
- http://www.eskimo.com/~scs/C-faq.top.html
-
- Disclaimer:
- I've only been doing this for a year, and I'm all self taught, so you
- might not want to trust my advice too much. Check my code with someone
- who knows. . .
-
-